package com.softhinker.ke24.unit2.data;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.text.NumberFormat;
import java.util.logging.SimpleFormatter;

import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import org.jgap.Chromosome;
import org.jgap.IChromosome;

import com.softhinker.ke24.unit2.MainFace.DataPanelCreator;

public class DataPanel implements DataPanelCreator {
	private JTable dataTable;
	private DefaultTableModel tableModel;
	private JPanel dataPanel = new JPanel();
	private JPanel headerPanel = new JPanel();
	private String header = "Fitness = sum[(Xi - AV)^2] = ";	
	private JLabel tableHeader = new JLabel(header);
	private String iterationHeader = "Iteration ";
	private JLabel iterationLabel = new JLabel(iterationHeader);
	private String mutationHeader = "Mutation rate = ";
	private JLabel mutationLabel = new JLabel(mutationHeader);
	private DataRetriever dataRetriever;
	private Object[][] originalData;
	
	public JComponent createDataPanel(DataRetriever dataRetriever) {
		this.dataRetriever = dataRetriever;
		//tableModel = new DefaultTableModel(dataRetriever.retrieveData(), dataRetriever.getColumnNames());		
		this.originalData = dataRetriever.retrieveData();
		tableModel = new DefaultTableModel(originalData, dataRetriever.getColumnNames());
		dataTable = new JTable();
		dataTable.setModel(tableModel);
		dataTable.setFillsViewportHeight(true);
		JScrollPane scrollPane = new JScrollPane(dataTable);
		
		headerPanel.setLayout(new GridLayout(1,2));
		headerPanel.add(tableHeader);
		headerPanel.add(iterationLabel);
		headerPanel.add(mutationLabel);
		
		dataPanel.setLayout(new BorderLayout());
		dataPanel.add(headerPanel, BorderLayout.NORTH);		
		dataPanel.add(scrollPane, BorderLayout.CENTER);
		return dataPanel;
	}

	public void onBetterSolutionFound(DataRetriever dataRetriever, double fitnessValue) {
		tableModel.setDataVector(dataRetriever.retrieveData(), dataRetriever.getColumnNames());
		tableModel.fireTableDataChanged();
		tableHeader.setText(header + fitnessValue);
		this.dataPanel.repaint();
	}
	
	public void onNewIteration(int count) {
	    iterationLabel.setText(iterationHeader + count);
	}
	
	public void onNewMutationRate(double mutationRate) {
	    NumberFormat fmt = NumberFormat.getInstance();
	    fmt.setMinimumFractionDigits(2);
	    mutationLabel.setText(mutationHeader + fmt.format(100/mutationRate) + "%"); 
	}
	
	public void reset() {
	    tableModel.setDataVector(originalData, dataRetriever.getColumnNames());
        tableModel.fireTableDataChanged();
        tableHeader.setText(header);
        this.dataPanel.repaint();
	}
}
